/**
 * 定义小时数据模块
 */
(function(window, angular, undefined){
    var module = angular.module('water.apps.sw.homePage.homePageManager', ['water.entity.bcDeviceMonitorParam',
        'water.entity.bcSendPlatform',
        'water.entity.bcSendPlatformParam',
        'water.common.EcharService',
        'water.common.dateUtil',
        'water.entity.strategy',
        'water.entity.monitorData']);

    module.controller('homePageController',function($rootScope,$scope,
                                                              $bcDeviceMonitorParamService,
                                                              $bcSendPlatformParamService,
                                                              $strategyService,
                                                              $monitorDataService,
                                                              $bcSendPlatformService,
                                                              $EcharService,$dateUtil){

        /**
         * 发送目标平台
         */
        $scope.sendPlatforms;

        /**
         * 参数列表
         */
        $scope.parmList;

        /**
         * 选择的平台Id
         */
        $scope.selectPlatformId;

        /**
         * 选择的平台
         */
        $scope.selectPlatform;

        /**
         * 监控数据
         */
        $scope.monitorData;

        /**
         * 数据分页获取器
         */
        $scope.dataGetter;

        /**
         * 查询开始时间
         */
        $scope.startDate;

        /**
         * 查询结束时间
         */
        $scope.endDate;

        /**
         * 查询开始小时
         */
        $scope.startHour = '11';

        /**
         * 查询结束小时
         */
        $scope.endHour = '12';

        /**
         * 对应平台的数据策略
         */
        $scope.strategyMap;

        /**
         * 数据类型
         */
        $scope.dataTypes = [
            {k:'MINUTES',v:'分钟数据'},
            {k:'HOUR',v:'小时数据'},
            {k:'DAY',v:'天数据'}
        ];

        /**
         * 小时选择器数据源
         */
        $scope.hours = [];

        /**
         * 选择的数据类型
         */
        $scope.selectDataType = 'HOUR';

        /**
         *数据信息，包含分页
         */
        $scope.data;

        /**
         * 数据定时获取器
         */
        $scope.getDataInterval;

        /**
         * 当前数据定时获取器
         */
        $scope.getCurDataInterval;

        /**
         * 当前数据
         */
        $scope.curDataList = {};

        /**
         * 查询按钮点击事件
         */
        $scope.onSearchClick = function(){
            $scope.getMonitorData();
        }


        /**
         * 发送平台选事件
         */
        $scope.onSendPlatformChange = function(key,item){
            $scope.setPlatform(item.data);
        }

        /**
         * 设置平台
         */
        $scope.setPlatform = function(platform){
            $scope.selectPlatform = platform;
            $scope.selectPlatformId = platform.PLATFORM_ID;

            $scope.getMonitorParams($scope.selectPlatformId);

            $strategyService.getListByPlatform($scope.selectPlatformId).then(function(data){
                $scope.strategyList = data;
                $scope.strategyMap = {};

                for(var i=0;i<data.length;i++){
                    var strategy = data[i];
                    $scope.strategyMap[strategy.dataType] = strategy.strategyId;
                }

                $scope.getMonitorData();
            });
        }

        /**
         * 数据类型选择事件
         */
        $scope.onDataTypeChange = function(key,item){
            var statisDataType = "MINUTES,HOUR,DAY";
            if(statisDataType.indexOf(key)>=0){
                $scope.isStatisDataType = true;
            }
            else{
                $scope.isStatisDataType = false;
            }
            $scope.getMonitorData();
        }

        /**
         * 获取发送目标平台
         */
        $scope.getSendPlatforms = function(){

            $bcSendPlatformService.getModelList().then(function(data){

                var platforms = [];

                for(var i=0;i<data.length;i++){
                    platforms.push({
                        v:data[i].NAME,
                        k:data[i].PLATFORM_ID,
                        data:data[i]
                    });
                }

                $scope.sendPlatforms = platforms

                if(data.length > 0){
                    $scope.setPlatform(data[0]);
                }
            });
        }

        /**
         * 获取站点所有的参数
         */
        $scope.getMonitorParams = function(platformId){
            $bcSendPlatformParamService.getListForReport(platformId).then(function(data){

                var params = [];
                for(var i=0; i<data.length; i++){

                    var item = data[i];
                    var descText = "";

                    if(item.ALARM_DOWN && item.ALARM_DOWN){
                        descText = item.ALARM_DOWN + "~" + item.ALARM_UP + "["+item.UNIT+"]";
                    }
                    else if(item.ALARM_DOWN == null && item.ALARM_DOWN == null){
                        descText = "["+item.UNIT+"]";
                    }
                    else if(item.ALARM_DOWN){
                        descText = "<" + item.ALARM_DOWN + "["+item.UNIT+"]";
                    }
                    else if(item.ALARM_UP){
                        descText = ">" + item.ALARM_UP + "["+item.UNIT+"]";
                    }

                    params.push({
                        parmName:item.PARAM_NAME,
                        name:item.PARAM_CODE_BUS,
                        descText:descText
                    });
                }
                $scope.parmList = params;
                //默认全选
                for(var i=0;i<$scope.parmList.length;i++){
                    $scope.parmList[i].checked = true;
                }
            });
        }

        /**
         * 获取监测数据
         */
        $scope.getMonitorData = function(){
            var queryObj = $scope.getQueryObj();

            if(queryObj==null){
                return
            }

            /**
             * 范围限制，避免过大数据量的查询发生,86399000为一天
             * 分钟1天,小时7天天30天
             */
            var start = new Date(Date.parse(queryObj.START));
            var end = new Date(Date.parse(queryObj.END));
            var diff = end - start;

            if("MINUTES"==$scope.selectDataType){
                if(diff>86399000){
                    alert("分钟数据：时间跨度不能超过1天");
                        return;
                }
            }

            if("HOUR"==$scope.selectDataType){
                if(diff>86399000*7){
                    alert("小时数据：时间跨度不能超过7天");
                    return;
                }
            }

            if("DAY"==$scope.selectDataType){
                if(diff>86399000*30){
                    alert("天数据：时间跨度不能超过30天");
                    return;
                }
            }

            if(!queryObj ){
                console.error("请选择平台和数据类型");
                return;
            }

            $monitorDataService.getMonitorData(queryObj).then(function (data) {
                $scope.data = data;
                $scope.monitorData = data[0];
                $scope.initChar();
            });
        }

        /**
         * 获取查询参数
         */
        $scope.getQueryObj = function(){

            if( !$scope.selectPlatform || !$scope.selectDataType){
                return null;
            }

            var startTimeStr =$scope.startDate + " " +  $scope.startHour +  ":00:00";
            var endTimeStr = $scope.endDate + " " +  $scope.endHour +  ":59:59";
            var strategyId = $scope.strategyMap[$scope.selectDataType];
            var dataType;
            for(var i=0;i<$scope.dataTypes.length;i++){
                if($scope.dataTypes[i].k == $scope.selectDataType){
                    dataType = $scope.dataTypes[i].v;
                }
            }

            if($scope.selectDataType == 'SINGLE_DATA'){

            }

            var obj = {
                "START":startTimeStr,
                "END":endTimeStr,
                'strategyId':strategyId,
                'dataType':dataType
            }
            return obj;
        }

        /**
         * 初始化小时下拉选择数据
         */
        $scope.initHours = function(){
            for(var i=0;i<24;i++){
                $scope.hours.push({
                    k:i,
                    v:i+"时"
                });
            }
        }

        /**
         * 显示图表
         *
         * parmList:{
         *				parmName:'化学需氧量',
         *				name:'COD'
         *			}
         *
         * monitorData:{
         * 		DATATIME:"2017-11-13 16:06:00",
         *		MEAS_RE_COD:3,
         *		MEAS_RE_SS:4,
         *		MEAS_RE_pH:20
         * }
         */
        $scope.initChar = function(){

            $("#char_tb").empty();

            var arrValues = [];

            for(var i=0;i<$scope.parmList.length;i++){

                if(!$scope.parmList[i].checked){
                    continue;
                }

                var parm = $scope.parmList[i];
                var times = [];
                var values = {
                    name:parm.parmName,
                    data:[]
                };

                for(var j =$scope.monitorData.data.length-1;j>=0;j--){

                    var dataItem = $scope.monitorData.data[j];

                    if(!dataItem){
                        continue;
                    }

                    times.push(dataItem.DATATIME);

                    var value = dataItem['MEAS_RE_'+parm.name];
                    values.data.push(value);
                }

                if(parm.name=="011"){
                    arrValues.push(values);
                }
                if(parm.name=="060"){
                    arrValues.push(values);
                }
                if(parm.name=="101"){
                    arrValues.push(values);
                }
            }

            var title = $scope.selectDataType;
            var domId = 'chartotal';
            var div = $("<div id='"+domId+"' ></div>").css({width:(Map_W-100),height:500});
            $("#char_tb").append(div);
            $EcharService.showMultipleSeries(domId,title,times,arrValues);
        }

        /**
         * 图表视图，勾选参数事件
         */
        $scope.checkedParm = function($event,parmIndex){
            $scope.parmList[parmIndex].checked = $event.target.checked;
            $scope.initChar();
        }

        /**
         * 获取策略
         */
        $scope.getStrategys = function(){
            $strategyService.getListByPlatform($scope.selectPlatformId).then(function(data){
                $scope.strategyList = data;
            });
        }

        $scope._init = function(){
            var date = new Date();
            date = $dateUtil.addHour(date,-5);
            $scope.startDate = $dateUtil.formatDate(date,'yyyy-MM-dd');
            $scope.startHour = date.getHours();

            date = $dateUtil.addHour(date,5);

            $scope.endDate = $dateUtil.formatDate(date,'yyyy-MM-dd');
            $scope.endHour = date.getHours();

            $scope.getSendPlatforms();
            $scope.initHours();
        }

        /**
         * 开始获取数据
         */
        $scope.startGetData = function(){
            $scope.getDataInterval = setInterval(function(){
                $scope.getData();
            },'300000');
        }

        /**
         * 获取数据
         */
        $scope.getData = function(){
            var date = new Date();
            date = $dateUtil.addHour(date,-5);
            $scope.startDate = $dateUtil.formatDate(date,'yyyy-MM-dd');
            $scope.startHour = date.getHours();
            date = $dateUtil.addHour(date,5);
            $scope.endDate = $dateUtil.formatDate(date,'yyyy-MM-dd');
            $scope.endHour = date.getHours();
            $scope.getMonitorData();
        }


        /**
         * 开始获取当前数据
         */
        $scope.startGetCurData = function(){
            $scope.getCurDataInterval = setInterval(function(){
                $scope.getCurData();
            },'10000');
        }

        /**
         * 获取当前数据
         */
        $scope.getCurData = function(){
            $monitorDataService.getSourceSingleData().then(function(data){
                var curData = data[0].data;
                for (var i=0;i<curData.length;i++){
                    for(var j=0;j<$scope.parmList.length;j++){
                        var parm = "MEAS_RE_" + $scope.parmList[j].name;
                        var value = curData[i][parm];
                        var dateTime = curData[i].DATATIME;
                        if(typeof(value) != "undefined"){
                            $scope.curDataList[parm] = value;
                            $scope.curDataList[parm +"_DATATIME"] = dateTime.slice(10);
                        }
                    }
                }
            });
        }

        $scope._init();
        $scope.startGetData();
        // $scope.startGetCurData();
    });
}(window, angular));